package com.guyu.plugin.mybatis.config;


import com.guyu.plugin.mybatis.helper.MybatisFlexHelper;
import com.guyu.plugin.mybatis.listener.FlexUserListener;
import com.mybatisflex.core.tenant.TenantFactory;
import com.mybatisflex.spring.boot.MybatisFlexAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

import java.util.Objects;

@AutoConfiguration(before = MybatisFlexAutoConfiguration.class)
public class MybatisFlexRegister {

    @Bean
    @ConditionalOnProperty(name = "mybatis-flex.configuration.tenantEnable", havingValue = "true", matchIfMissing = true)
    public TenantFactory tenantFactory() {
        return () -> {
            FlexUserListener flexUserListener = MybatisFlexHelper.getUserListener();
            if (Objects.isNull(flexUserListener)) {
                return new Object[]{};
            }
            Long[] tenantIds = flexUserListener.getTenantIds();
            if (Objects.isNull(tenantIds)) {
                return new Object[]{};
            }
            return new Object[]{tenantIds};
        };
    }
}
